﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using WebUtils;
#if PocketPC
using OpenNETCF.Security.Cryptography;
#else
#endif

namespace OAuth.SignatureMethods
{

    public sealed class Hmacsha1 : SignatureMethod
    {
        private static Hmacsha1 instance;
        private Hmacsha1() { }

        public static Hmacsha1 Instance
        {
            get
            {
                if (instance == null)
                    instance = new Hmacsha1();
                return instance;
            }
        }

        public override string Name { get { return "HMAC-SHA1"; } }

        public override string CreateSignature(
            IUnsignedWebRequest pRequest, 
            IOAuthSessionParameter pSessionParameter,
            IEnumerable<UnEncodedURLParameter> pOAuthParameters)
        {
            var text = string.Format(
                "{0}&{1}&{2}",
                ParameterEncoder.ValueEncode(pRequest.Verb.ToString().ToUpper()),
                ParameterEncoder.ValueEncode(base.GetNormalizedRequestUrl(pRequest.Address)),
                ParameterEncoder.ValueEncode(base.GetNormalizedRequestParameters(
                    pRequest,
                    pOAuthParameters)));

            var key = string.Format("{0}&{1}", 
                        ParameterEncoder.ValueEncode(pSessionParameter.ConsumerSecret),
                        string.IsNullOrEmpty(pSessionParameter.TokenStorage.TokenSecret) 
                            ? "" 
                            : ParameterEncoder.ValueEncode(pSessionParameter.TokenStorage.TokenSecret));

            HMACSHA1 hmacsha1 = new HMACSHA1(Encoding.UTF8.GetBytes(key));

            return Convert.ToBase64String(hmacsha1.ComputeHash(System.Text.Encoding.UTF8.GetBytes(text)));
        }
    }
}
